package tuwien.big.formel0.utilities;

import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.RollbackException;
import tuwien.big.formel0.entities.Player;
import java.util.ArrayList;
import java.util.List;
import javax.faces.model.SelectItem;
import tuwien.big.formel0.picasa.RaceDriver;
import tuwien.big.formel0.picasa.RaceDriverService;

/**
 *
 * @author Dieter
 */
public class Utility {
    private static EntityManager em;
    private static ArrayList<SelectItem> avatarList;
    
    static {
        em = Persistence.createEntityManagerFactory("lab4").createEntityManager();
        Player p = new Player();
        p.setName("t");
        p.setPassword("t");
        p.setFirstname("Testus");
        p.setLastname("Tester");
        p.setSex("m");
        p.setBirthday("01.04.1984");
        storePlayer(p);
        loadPicasaStuff();
    }

    public static String getResourceText(FacesContext ctx,
            String bundleName, String key) {
        String text;
        try {
            Application app = ctx.getApplication();
            ResourceBundle bundle = app.getResourceBundle(
                    ctx, bundleName);
            text = bundle.getString(key);
        } catch (MissingResourceException e) {
            return "???" + key + "???";
        }

        return text;
    }
    
    public static boolean storePlayer(Player player) {
        if (em == null) return false;
        try {
            em.getTransaction().begin();
            em.persist(player);
            em.getTransaction().commit();
        } catch (RollbackException e) {
            return false;
        }
        return true;
    }
    
    public static Player loadPlayer(String name) {
        return em.find(Player.class, name);
    }
    
    private static void loadPicasaStuff() {
        List<RaceDriver> list;
        try {
            list = new RaceDriverService().getRaceDrivers();
        } catch (IOException ex) {
            list = new ArrayList<RaceDriver>();
        } catch (ServiceException ex) {
            list = new ArrayList<RaceDriver>();
        }
        avatarList = new ArrayList<SelectItem>();
        em.getTransaction().begin();
        for (RaceDriver av : list) {
            em.persist(av);
            avatarList.add(new SelectItem(av));
        }
        em.getTransaction().commit();
    }

    /**
     * @return the avatarList
     */
    public static ArrayList<SelectItem> getAvatarList() {
        return avatarList;
    }
}
